<template>
	<view>
		<dev-navbar :title="title"></dev-navbar>
		<dev-calendar :is-open="false" @select="getHealthTask" ref="calendar" :endTime="endTime"></dev-calendar>
		<view class="all-tasks">
			<view v-show="item.taskContent" class="every-task justify-content-l" v-for="(item,index) in taskList"
				:key="index">
				<view class="align-items-l">
					<dev-svg-image mode="image" :imageUrl="item.taskLibraryIcon" width="194" height="174">
					</dev-svg-image>
					<view class="task-details">
						<view class="task-name">
							{{item.taskLibraryName || ''}}
						</view>
						<view class="task-progress ellipsis">
							{{item.taskContent || ''}}
						</view>
						<view class="task-reward align-items-l">
							<text style="margin-right: 10rpx;">+{{item.points}}</text>
							<dev-svg-image width="44" height="36" mode="image"
								image-url="shoppingMall/3134AD32EBD94B39BBDE51AEEDEFA7B0.png">
							</dev-svg-image>
						</view>
					</view>
				</view>

				<view @tap="jumpDeatils(item)" v-if="item.thematicPlan==1  && item.todayFlag ==1"
					:class="item.taskStatus==1?'incomplete':'complete'">
					{{item.taskLibraryName}}
				</view>
				<view @tap="showTasks(item)" v-if="item.thematicPlan !=1 && item.todayFlag ==1"
					:class="item.taskStatus==1?'incomplete':'complete'">
					{{item.taskStatus==1?'已完成':'去打卡'}}
				</view>
				<!-- //是否完成 -->
				<view class="complete-or-not" v-show="item.todayFlag ==0 && item.taskStatus==1">
					<dev-svg-image mode="image" width="156" height="156"
						imageUrl="http://static.bsyjk.cn/accomplish/122738696B9040F2866A0D25F5FD96BA.png">
					</dev-svg-image>
				</view>
			</view>
		</view>

		<nodata v-if="taskList.length==0 || !taskList" top="30" text="暂无计划"></nodata>

		<u-popup v-model="popupShow" mode="center" :mask-close-able="false">
			<view>
				<!-- 喝水任务 -->
				<view class="drinking-information" v-show="taskType==1">
					<view class="water-cup">
						<teacup-loading :num="currentTaskInformation.num" :finishNum="currentTaskInformation.finishNum">
						</teacup-loading>
					</view>
					<view class="drinking-data">
						需喝水{{currentTaskInformation.spare*currentTaskInformation.num}}mL
					</view>
					<view class="drinking-data">
						已经喝水{{currentTaskInformation.spare*currentTaskInformation.finishNum}}mL（{{currentTaskInformation.finishNum}}杯）
					</view>
				</view>
				<view v-show="taskType==1">
					<dev-button v-if="currentTaskInformation.taskStatus ==0" @tapDev="punchTheClock" width="656"
						height="90" radius="45" bgColor="#81C042" top="50" font-size="34">喝水+1
					</dev-button>
					<dev-button @tapDev="popupShow = false" width="656" height="90" radius="45" top="30" font-size="34">
						{{currentTaskInformation.taskStatus ==1?'关闭':'取消'}}
					</dev-button>
				</view>
				<!-- 视频任务 -->
				<view class="video-box" v-show="taskType==2">
					<video @play="firstPlay" loop style="width:656rpx" id="myVideo"
						:src="currentTaskInformation.taskMaterialVOS[0].taskMaterialUrl" @error="videoErrorCallback"
						:danmu-list="danmuList" enable-danmu :controls="false"></video>
					<view class="description-description">
						{{currentTaskInformation.taskMaterialVOS[0].taskMaterialDesc || '跟着视频做运动'}}
					</view>
				</view>
				<view v-show="taskType==2">
					<!-- v-if="currentTaskInformation.taskStatus ==0" -->
					<dev-button @tapDev="playVideo" width="656" height="90" radius="45" bgColor="#81C042" top="50"
						font-size="34">
						{{isFirstPlay?'开始跟着视频做':whetherPlaying?'休息会':'继续运动'}}
					</dev-button>
					<dev-button @tapDev="punchTheClock" v-if="!isFirstPlay && currentTaskInformation.taskStatus!=1"
						width="656" height="90" radius="45" top="30" font-size="34">
						不做了
					</dev-button>

					<dev-button v-else @tapDev="closeVideo()" width="656" height="90" radius="45" top="30"
						font-size="34">
						{{currentTaskInformation.taskStatus ==1?'关闭':'取消'}}
					</dev-button>
				</view>

				<!-- 图片任务 -->
				<view class="picture-task" v-show="taskType==3">
					<dev-svg-image mode="image" :imageUrl="currentTaskInformation.taskLibraryIcon" width="655"
						height="448"></dev-svg-image>
					<view class="description-description">
						{{currentTaskInformation.taskDesc|| '有节奏的深呼吸，可增加身体含氧量，舒缓压力'}}
					</view>
				</view>
				<!-- 音频任务 -->
				<view class="audio-task" v-show="taskType==4">
					<dev-svg-image radius="20" width="650" height="650" mode="image"
						:imageUrl="currentTaskInformation.taskMaterialVOS[currentIndex].dynamicGraphUrl">
					</dev-svg-image>
					<scroll-view class="scroll-view_H" scroll-x="true" scroll-left="120">
						<view @tap.stop="switchMusic(index)"
							:class="index==currentIndex?'activation-options':'not-active-options'"
							v-for="(item,index) in currentTaskInformation.taskMaterialVOS" :key="index">
							<view class="every-music">
								<dev-svg-image mode="image" :imageUrl="item.taskMaterialIcon"></dev-svg-image>
								{{item.taskMaterialDesc || ''}}
							</view>
						</view>
					</scroll-view>
				</view>

				<view v-show="taskType==3 || taskType==4">
					<dev-button v-show="taskType==3" @tapDev="followThePicture()" width="656" height="90" radius="45"
						bgColor="#81C042" top="50" font-size="34">
						开始跟着画面做
					</dev-button>
					<dev-button v-show="taskType==4" @tapDev="musicSwitch()" width="656" height="90" radius="45"
						bgColor="#81C042" top="50" font-size="34">
						{{whetherPlaying?'休息会':'继续运动'}}
					</dev-button>
					<dev-button @tapDev="punchTheClock" v-if="whetherPlaying && currentTaskInformation.taskStatus!=1"
						width="656" height="90" radius="45" top="30" font-size="34">
						不做了
					</dev-button>
					<dev-button v-else @tapDev="closeVideo()" width="656" height="90" radius="45" top="30"
						font-size="34">
						{{currentTaskInformation.taskStatus ==1?'关闭':'取消'}}
					</dev-button>
				</view>
			</view>
		</u-popup>

		<!-- 设备选择 -->
		<u-select v-if="show" v-model="show" @confirm="selectEntryMethod" :default-value="0" :list="list" title="请选择"
			cancel-color="#2EA7E0" confirm-color="#2EA7E0"></u-select>
		<dev-iphone-bottom></dev-iphone-bottom>
	</view>
</template>

<script>

import uPopup from "@/uview-ui/components/u-popup/u-popup.vue"
import uSelect from "@/uview-ui/components/u-select/u-select.vue"
	import teacupLoading from '@/pagesHome/components/teacup-loading.vue'
	import dayjs from '@/common/utils/day/day.js'
	import devCalendar from '@/pagesHome/components/dev-calendar/dev-calendar.vue'
	export default {
		components: {
			teacupLoading,
			devCalendar,
			uPopup,
			uSelect
		},
		data() {
			return {
				title: '健康任务',
				complete: 0,
				show: false, //显示选择 数据录入方式
				popupShow: false, //自定义内容弹框
				taskType: 1, //1 喝水；2视频 ；3图片 ； 4音频

				list: [{
						value: '1',
						label: '设备录入'
					},
					{
						value: '2',
						label: '手动录入'
					}
				],

				taskList: [], //任务列表

				timeLength: '', //时长 或者次数
				topicId: '', //素材id（文章、视频、音频id）
				userTaskDetailId: '', //任务详情id

				currentTaskInformation: '', //当前任务信息

				videoContext: '', //视频信息
				whetherPlaying: false, //是否播放中
				timingTime: '', //定时时间
				isFirstPlay: true, //

				currentIndex: 0, //当前选中的音频下标
				audioInformation: '', //音频信息
				isTimedStart: false, //判断定时器是否开始
				endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), //禁止选择当前日期之后的日期





				current: {
					poster: 'https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-uni-app-doc/7fbf26a0-4f4a-11eb-b680-7980c8a877b8.png',
					name: '致爱丽丝',
					author: '暂无',
					src: 'http://static.bsyjk.cn/ABC/96286C52833D493DBDFDB74D1445337C.mpeg',
				},
				audioAction: {
					method: 'pause'
				}


			};
		},
		onLoad() {
			this.videoContext = uni.createVideoContext('myVideo'); //创建视频实例指向video
		},
		onUnload() {
			this.audioInformation = '';
			if (this.isTimedStart) {
				clearInterval(this.timingTime);
				this.videoContext.pause();
				this.whetherPlaying = false;
				this.isTimedStart = false;
			}
		},
		onShow() {
			this.$refs.calendar.throwCurrentTime();
		},
		methods: {
			//打卡
			punchTheClock() {
				let _this = this;
				//清楚定时器
				if (this.isTimedStart) {
					clearInterval(this.timingTime);
					this.videoContext.pause();
					this.whetherPlaying = false;
					if (this.currentTaskInformation.taskLibraryType === 'AUDIO') {
						this.audioInformation.stop()
					}
					this.isTimedStart = false;
				}
				this.$https.post(global.apiUrls.punchTheClock, {
					timeLength: this.timeLength, //时长 或者次数
					topicId: this.topicId, //素材id（文章、视频、音频id）
					userTaskDetailId: this.userTaskDetailId //任务详情id
				}).then(res => {
					if (res.data.code === 1000) {
						this.$refs.calendar.throwCurrentTime();
						//不等 视频 关闭弹框
						if (this.currentTaskInformation.taskLibraryType !== 'VIDEO' && this.currentTaskInformation
							.taskLibraryType !== 'AUDIO') {
							this.popupShow = false;
							this.$message.info('打卡成功')
						}

						if (this.currentTaskInformation.taskLibraryType === 'VIDEO' || this.currentTaskInformation
							.taskLibraryType === 'AUDIO') {
							if (this.timeLength >= this.currentTaskInformation) {
								this.currentTaskInformation.taskStatus = 1; //已完成
								this.popupShow = false;
								this.$message.info('任务完成')
							}
							this.isFirstPlay = true;
							this.timingTime = '';
						}

					} else {
						this.timingTime = '';
						setTimeout(() => {
							uni.showModal({
								title: '提示',
								content: res.data.message,
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										_this.popupShow = false;
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
						}, 500)

					}

				})
			},

			//播放视频
			playVideo() {
				//whetherPlaying true正在播放中
				if (this.whetherPlaying) {
					this.videoContext.pause();
					this.whetherPlaying = false;
				} else {
					if (this.isFirstPlay) {
						if (this.currentTaskInformation.taskStatus == 0) {
							this.scheduledTask();
						}
						this.isFirstPlay = false;
					}
					//开始计算时间
					this.videoContext.play();
					this.whetherPlaying = true;
				}
			},
			//关闭视频弹框
			closeVideo() {
				this.isFirstPlay = true;
				this.popupShow = false;
				this.audioInformation = '';
				if (this.isTimedStart) {
					clearInterval(this.timingTime);
					this.isTimedStart = false;
				}
				this.currentIndex = 0;
			},
			//判断是不是首次播放
			firstPlay() {
				if (this.isFirstPlay) {
					this.playVideo();
					setTimeout(() => {
						this.isFirstPlay = false;
					}, 100)
				}
			},
			//计算定时任务
			scheduledTask() {
				if (this.isTimedStart) return
				this.isTimedStart = true;
				this.timingTime = setInterval(() => {
					if (this.whetherPlaying) {
						this.timeLength++
						if (this.timeLength >= this.currentTaskInformation.num * 60) {
							clearInterval(this.timingTime)
							this.punchTheClock();
							return
						}
						console.log(this.timeLength, '计算的时间')
					}
				}, 1000);
			},
			//跟着画面做
			followThePicture() {
				this.taskType = 4;
				this.audioInformation = uni.createInnerAudioContext();
				this.audioInformation.autoplay = true;
				this.audioInformation.loop = true;
				this.audioInformation.startTime = 0;
				this.audioInformation.src = this.currentTaskInformation.taskMaterialVOS[this.currentIndex].taskMaterialUrl;
				this.audioInformation.onPlay(() => {
					this.scheduledTask();
					console.log(this.whetherPlaying, '开播放了,计时任务开始')
				})
				this.whetherPlaying = true;
			},
			//音乐开关
			musicSwitch() {
				if (this.whetherPlaying) {
					this.whetherPlaying = false;
					this.audioInformation.stop(() => {
						console.log(this.whetherPlaying, '暂停播放,计时任务暂停')
					})
				} else {
					this.whetherPlaying = true;
					this.audioInformation.play(() => {
						console.log(this.whetherPlaying, '开播放了,计时任务开始')
					})
				}

			},
			//切换音乐
			switchMusic(index) {
				this.currentIndex = index;
				this.audioInformation.src = this.currentTaskInformation.taskMaterialVOS[this.currentIndex].taskMaterialUrl;
				this.audioInformation.play()
				this.whetherPlaying = true;
			},


			//显示任务
			showTasks(val) {
                //判断任务的时间
                this.$https.post(global.apiUrls.saveJudge, {
                	userTaskDetailId: val.userTaskDetailId
                }).then(res => {
                	if (res.data.code === 1000 && res.data.success) {
                		//规律起床
                		if (val.taskLibraryType === 'PUNCH_IN') {
                			this.currentTaskInformation = val;
                			this.timeLength = 1;
                			this.userTaskDetailId = val.userTaskDetailId;
                			this.punchTheClock(); //打卡
                		}
                		//去喝水
                		if (val.taskLibraryType === 'DRINK_WATER') {
                			this.currentTaskInformation = val;
                			this.timeLength = 1;
                			this.userTaskDetailId = val.userTaskDetailId;
                			this.taskType = 1;
                			this.popupShow = true;
                		}
                		//视频
                		if (val.taskLibraryType === 'VIDEO') {

                			this.currentTaskInformation = val;
                			this.userTaskDetailId = val.userTaskDetailId;
                			this.topicId = val.taskMaterialVOS[0].taskMaterialId;
                			this.taskType = 2;
                			this.timeLength = Math.round(val.finishNum * 60);
                			this.popupShow = true;
                		}
                		//音频
                		if (val.taskLibraryType === 'AUDIO') {
                		    this.punchTheClock(); //打卡
                			this.currentTaskInformation = val;
                			this.userTaskDetailId = val.userTaskDetailId;
                			this.topicId = val.taskMaterialVOS[0].taskMaterialId;
                			this.taskType = 3;
                			this.timeLength = Math.round(val.finishNum * 60);
                			this.popupShow = true;
                		}
                		//设备 手动测量
                		if (val.taskLibraryType === 'MEASURE') {
                		    //this.punchTheClock(); //打卡
                			this.timeLength = 1;
                			this.currentTaskInformation = val;
                			this.userTaskDetailId = val.userTaskDetailId;
                			if (val.deviceFlag == 1) {
                				this.show = true;
                			}
                		}
                		//阅读类的
                		if (val.taskLibraryType === 'READING') {
                			this.timeLength = 1;
                			this.currentTaskInformation = val;
                			this.userTaskDetailId = val.userTaskDetailId;
                			this.$urouter.navigateTo({
                				url: '/pages/subpackage/find/articleDetails/details',
                				params: {
                					pageTitle: val.taskLibraryName, //文章类型
                					id: JSON.parse(val.taskContentJson).contentId, //文章id
                					taskStatus:val.taskStatus,
                					taskType:'READING'
                				}
                			});

                		}
                	}else{
                        this.timingTime = '';
                        setTimeout(() => {
                        	uni.showModal({
                        		title: '提示',
                        		content: res.data.message,
                        		showCancel: false,
                        		success: function(res) {
                        			if (res.confirm) {
                        				_this.popupShow = false;
                        			} else if (res.cancel) {
                        				console.log('用户点击取消');
                        			}
                        		}
                        	});
                        }, 500)
                    }
                })


			},
			//选择录入方式
			selectEntryMethod(e) {
				if (e[0].value == 1) {
					console.log(this.currentTaskInformation.itemCode, '设备录入');
					//血压设备录入
					if (this.currentTaskInformation.itemCode === 'BLOOD_PRESSURE') {
						this.$urouter.navigateTo({
							url: '/pagesHome/manual-input/equipment-records',
							params: {
								type: '1', //1是打卡
								data: JSON.stringify(this.currentTaskInformation)
							}
						});
					}
					//体重
					if (this.currentTaskInformation.itemCode === 'WEIGHT') {
						this.$urouter.navigateTo({
							url: '/pages/subpackage/home/equipment/balance',
							params: {
								type: '1', //1是打卡
								data: JSON.stringify(this.currentTaskInformation)
							}
						});
					}
					//尿酸
					if (this.currentTaskInformation.itemCode === 'URIC_ACID') {
						this.$urouter.navigateTo({
							url: '/pages/subpackage/home/equipment/uricAcid',
							params: {
								type: '1', //1是打卡
								data: JSON.stringify(this.currentTaskInformation)
							}
						});
					}
					//血糖
					if (this.currentTaskInformation.itemCode === 'BLOOD_SUGAR') {
						this.$urouter.navigateTo({
							url: '/pages/subpackage/home/equipment/bloodSugar',
							params: {
								type: '1', //1是打卡
								data: JSON.stringify(this.currentTaskInformation)
							}
						});
					}


				} else {
					console.log('手动录入')
					this.$urouter.navigateTo({
						url: '/pagesHome/manual-input/manual-input',
						params: {
							data: JSON.stringify(this.currentTaskInformation)
						}
					});
				}
			},


			//获取健康任务
			getHealthTask(val) {
				this.$https.get(global.apiUrls.healthTask, {
					taskDate: val.time,
					userId: global.userInfo.userId,
				}).then(res => {
					if (res.data.code === 1000) {
						this.taskList = res.data.result;
					}
				})
			},
			//跳转界面
			jumpDeatils(item) {
				if (item.thematicPlan == 1) {
					if (item.typeId == 1 || item.typeId == 2 || item.typeId == 3 || item.typeId == 4 || item
						.typeId == 5 ||
						item.typeId == 9) {
						this.$urouter.navigateTo({
							url: '/pages/subpackage/find/articleDetails/details',
							params: {
								task: item.taskStatus, //任务状态
								id: item.topicId,
								stepId: item.userTaskDetailId,
								givePoint: item.points,
								typeId: item.typeId,
								pageTitle: item.taskLibraryName
							}
						});
					}
					if (item.typeId == 8) {
						this.$urouter.navigateTo({
							url: '/pages/subpackage/home/oneAccess/evaluating',
							params: {
								task: item.taskStatus, //任务状态
								id: item.topicId,
								stepId: item.userTaskDetailId,
								givePoint: item.points,
								typeId: item.typeId,
								pageTitle: item.taskLibraryName
							}
						});
					}
					if (item.typeId == 10) {
						this.$urouter.navigateTo({
							url: '/pages/subpackage/find/video-detail/video-detail',
							params: {
								task: item.taskStatus, //任务状态
								id: item.topicId, //-------------------------------
								stepId: item.userTaskDetailId,
								givePoint: item.points,
								typeId: item.typeId,
								pageTitle: item.taskLibraryName
							}
						});
					}
					if (item.typeId == 11) {
						this.$urouter.navigateTo({
							url: '/pages/subpackage/find/postAmessage/postAmessage',
							params: {
								task: item.taskStatus, //任务状态
								stepId: item.userTaskDetailId,
								givePoint: item.points,
								typeId: item.typeId,
								pageTitle: item.taskLibraryName
							}
						});
					}
					if (item.typeId == 12) {
						this.userTaskStep(item.userTaskDetailId, '')
						uni.switchTab({
							url: '/pages/tab/college'
						})
					}
				}
			},

			// 用户完成一个小目标
			userTaskStep(taskStepId, taskAppendix) {
				let _this = this;
				_this.disabled = true;
				let fdata = {
					userId: uni.getStorageSync(global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z').userId,
					userStepId: taskStepId,
					taskAppendix: taskAppendix
				}
				this.$api.put(global.apiUrls.userTaskStep, fdata).then(res => {
					if (res.data.code == 1000) { //完成任务
						uni.$emit('collegeTask', 1)
					} else {}
				}).catch(err => {})
			},

		}
	}
</script>

<style lang="scss">
	.scroll-view_H {
		white-space: nowrap;
		width: 656rpx;
		margin-top: 40rpx;
	}

	.activation-options {
		display: inline-block;
		width: 160rpx;
		height: 160rpx;
		background: #2EA7E0;
		border-radius: 14rpx;
		margin-right: 20rpx;
	}

	.not-active-options {
		display: inline-block;
		width: 160rpx;
		height: 160rpx;
		border-radius: 14rpx;
		margin-right: 20rpx;

		border: 2rpx solid #979797;
	}

	.every-music {
		width: 160rpx;
		height: 160rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #fff;
		font-size: 30rpx;
		font-weight: 500;
	}


	.all-tasks {
		padding: 30rpx 24rpx;

		.every-task {
			background-color: #fff;
			border-radius: 16rpx;
			overflow: hidden;
			margin-bottom: 30rpx;
			position: relative;

			.complete-or-not {
				position: absolute;
				top: 10rpx;
				right: 30rpx;
			}

			.task-details {
				margin-left: 12rpx;

				.task-name {
					font-size: 34rpx;
					font-weight: 500;
					color: #4A4A4A;
				}

				.task-progress {
					width: 300rpx;
					margin-top: 20rpx;
					font-size: 24rpx;
					font-weight: 400;
					color: #F5A623;
				}

				.task-reward {
					margin-top: 20rpx;
					font-size: 30rpx;
					font-weight: 500;
					color: #333333;
				}
			}
		}

		.incomplete {
			width: 150rpx;
			height: 66rpx;
			background: #E2E1E2;
			border-radius: 16rpx 0rpx 0rpx 16rpx;
			text-align: center;
			line-height: 66rpx;
			font-size: 30rpx;
			font-weight: 400;
			color: #9B9B9B;
		}

		.complete {
			width: 150rpx;
			height: 66rpx;
			background: #2EA7E0;
			border-radius: 16rpx 0rpx 0rpx 16rpx;
			text-align: center;
			line-height: 66rpx;
			font-size: 30rpx;
			font-weight: 400;
			color: #FFFFFF;
		}


	}

	.video-box {
		background-color: #FFFFFF;
		border-radius: 20rpx;

		.description-description {
			height: 146rpx;
			padding: 20rpx 16rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #4A4A4A;
			line-height: 55rpx;
		}
	}

	.picture-task {
		background-color: #FFFFFF;
		border-radius: 20rpx;

		.description-description {
			height: 146rpx;
			padding: 20rpx 16rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #4A4A4A;
			line-height: 55rpx;
		}
	}

	.audio-task {
		.audio-picture {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 656rpx;
			height: 564rpx;
			background-image: url('http://static.bsyjk.cn/shoppingMall/A58745153FD34D6A9C5C2D2D90782E7E.png');
			background-size: 100% 100%;
			font-size: 38rpx;
			font-weight: 400;
			color: #4A4A4A;
		}
	}

	.drinking-information {
		padding: 66rpx;
		border-radius: 20rpx;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
		align-items: center;

		.water-cup {
			margin-top: 20rpx;
			margin-bottom: 20rpx;
		}

		.drinking-data {
			font-size: 36rpx;
			font-weight: 400;
			color: #000000;
			line-height: 55rpx;
		}
	}
</style>
